package com.hns.can.common.web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.domain.ReturnResult;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.exception.ParameterFormatException;
import com.hns.frame.security.AppUserDetailsImpl;

/**
 * 基础控制器
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
public abstract class BaseController {
	
    protected static final Logger log = LoggerFactory.getLogger(BaseController.class);
	
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    
    /**
     * 取得当前登录用户
     * @return  登录用户的基本信息
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public AppUserDetailsImpl getCurrentUser() {
        try{
            return (AppUserDetailsImpl)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }catch(ClassCastException ce){
            throw new BusinessException(MsgType.KICK_OFF .getFlag(), "未登录，或回话过期");
        }
    }
    
    public SysUserEntity getPhoneCurrentUser() {
        SysUserEntity sysUserEntity = (SysUserEntity) request.getSession().getAttribute("PHONE_CURRENTUSER");
        return sysUserEntity;
    }
    
    
    /**
     * app取得当前登录用户
     * @return  登录用户的基本信息
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public AppUserDetailsImpl getAppCurrentUser() {
        try{
            return (AppUserDetailsImpl)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }catch(ClassCastException ce){
        	return null;
        }
    }
    
    
    /**
     * 
     * @Title:  getParameter_prefix
     * @Description: 获取request请求参数 带search_前缀
     * @return
     * Map<String,Object>
     */
    public Map<String, Object> getParameter_prefix() {
        Map<String, String[]> map = request.getParameterMap();
        Map<String, Object> searchParam = new LinkedHashMap<String, Object>();
        Set<Entry<String, String[]>> setEntry = map.entrySet();
        StringBuffer sps = new StringBuffer();
        String value = "";
        for (Entry<String, String[]> entry : setEntry) {
            if (entry.getKey().indexOf("search_") > -1) {
                String key = entry.getKey().replace("search_", "");
                if (entry.getValue().length > 0) {
                    value = entry.getValue()[0];
                    if (null != value && !"".equals(value)) {
                        searchParam.put(key, value);
                    }
                }
                request.setAttribute(entry.getKey(), value);
            }
        }
        return searchParam;
    }
    
    /**
     * 
     * @Title:  getParameter
     * @Description: 获取request请求参数 不带前缀
     * @return
     * Map<String,Object>
     */
    public Map<String, Object> getParameter() {
        Map<String, Object> sParaTemp = new LinkedHashMap<String, Object>();
        Map<String, String[]> map = request.getParameterMap();
        Set<Entry<String, String[]>> setEntry = map.entrySet();
        for (Entry<String, String[]> entry : setEntry) {
            String key = entry.getKey();
            String value = entry.getValue()[0];
            sParaTemp.put(key, value);
        }
        return sParaTemp;
    }
    
    /**
     * 
     * @Title:  getParameter
     * @Description: 获取request请求参数 json格式
     * @return
     * @throws ParameterFormatException
     * JSONObject
     */
    public JSONObject getParameter_JSON() throws  ParameterFormatException{
        JSONObject param = null;
        try {
            request.setCharacterEncoding("UTF-8");
            BufferedReader buff = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
            StringBuffer str =  new StringBuffer(2048);
            String s = null;
            while ((s = buff.readLine()) != null){
                str.append(s);
            }
            param = JSONObject.fromObject(str.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParameterFormatException("参数格式错误");
        }  
        return param;
    }
    
    
    /**
     * 操作成功，不弹出提示
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public ReturnResult getReturnResult(){
        return new ReturnResult();
    }
    
    /**
     * 操作成功,前台弹出msg的提示消息
     * @param msg
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public ReturnResult getReturnMsg(String msg){
        return new ReturnResult(msg, null);
    }
    
    /**
     * 操作成功,并返回相应的数据对象
     * @return
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    public ReturnResult getReturnResult(Object obj){
        return new ReturnResult(obj);
    }
}
